<?php

namespace App\Http\Resources\Base;

use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class BaseResource extends JsonResource
{
    public function __construct($resource)
    {
        parent::__construct($resource);
    }

    /**
     * @param Request $request
     *
     * @return JsonResponse|\Symfony\Component\HttpFoundation\JsonResponse
     */
    public function toResponse($request)
    {
        $response = parent::toResponse($request);

        $encodingOptions = config('app.debug') ? JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES + JSON_PRETTY_PRINT : 0;

        $data = $response->getData(true);

        $response->setData((array)$data);

        return $response->setEncodingOptions($encodingOptions);
    }

    public static function collection($resource)
    {
        $collection = tap(new CustomAnonymousResourceCollection($resource, static::class), function ($collection): void {
            if (property_exists(static::class, 'preserveKeys')) {
                $collection->preserveKeys = true === (new static([]))->preserveKeys;
            }
        });
        // 强制转移Code 类型
        $collection->with = (new self([]))->with;

        return $collection;
    }

    /**
     * @description 解析时间转 字符串
     *
     * @param null $dateTime
     *
     * @return null|string
     */
    public function parseDateTime($dateTime = null)
    {
        if (!$dateTime) {
            return $dateTime;
        }
        if ($dateTime instanceof Carbon) {
            $dateTime = $dateTime->toDateTimeString();
        }

        return $dateTime;
    }

    /**
     * @description 解析时间转 字符串
     *
     * @param null $dateTime
     *
     * @return null|string
     */
    public function parseDateTimeToTimestamp($dateTime = null)
    {
        if (!$dateTime) {
            return $dateTime;
        }
        if ($dateTime instanceof Carbon) {
            $dateTime = $dateTime->getTimestamp();
        }

        return $dateTime;
    }

    /**
     * @description 解析时间转 字符串
     *
     * @param null $dateTime
     *
     * @return null|string
     */
    public function parseDateTimeToTimestampMs($dateTime = null)
    {
        if (!$dateTime) {
            return $dateTime;
        }
        if ($dateTime instanceof Carbon) {
            $dateTime = $dateTime->getTimestampMs();
        }

        return $dateTime;
    }
}
